import { baseUrl } from "./url";
// import { Api } from "./index";
import { refreshTokens } from "./apis.js";

// Create a new Promise-based function to handle requests
function request(params) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + params.url,
      method: params.method || "POST",
      data: params.data || {},
      header: {
        token: uni.getStorageSync("userToken"),
        "content-type": params.contentType || "application/x-www-form-urlencoded",
      },
      success: (res) => {
        if (res.data.code == 200 || res.data.code == 1) {
          resolve(res.data.data);
        } else if (res.data.code == 101) {
          // Refresh token
		  let uid = uni.getStorageSync('uid');
          refreshTokens({uid}).then(async(result) => {
            uni.setStorageSync("userToken",result.token)
            return await request(params);
          }).then((data) => {
            resolve(data);
          }).catch((err) => {
            reject(err);
          });
        }else {
			if((res.data.code==0 && res.data.msg=='請先登錄') || res.data.code == 102){
				uni.showToast({
					title:"請重新登錄",
					mask:true,
					icon:"none"
				})
				setTimeout(()=>{
					uni.navigateTo({
						url:'/pages/index/index'
					})
				},1200)
			}else{
				reject(res.data);
			}
          
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}

export default function requests(params) {
  return request(params);
}